package com.chdwmp.product.system;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author WuJunyi
 * @create 2020-07-15 19:14
 **/
@Aspect
@Component
public class GlobalLogHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalLogHandler.class);
    ThreadLocal<Long> startTime = new ThreadLocal<>();



    @Pointcut("execution(public * com.chdwmp.product.controller.*Controller.*(..))")
    public void logPoint() {
    }

    @Before("logPoint()")
    public void doBeforeControllerPoint(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        StringBuffer requestURL = request.getRequestURL();

        logger.info("<====================================================================");
        logger.info("请求URL: " + request.getRequestURL().toString());
        logger.info("请求方法: " + request.getMethod());
        logger.info("请求IP : " + request.getRemoteAddr());
        logger.info("响应方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(pointcut = "logPoint()", returning = "result")
    public void doAfterControllerPoint(JoinPoint joinPoint, Object result) {
        logger.info("耗时（毫秒） : " + (System.currentTimeMillis() - startTime.get()));

        logger.info("返回数据: " + null == result || null == JSONObject.toJSON(result) ? "(空)" : JSONObject.toJSON(result).toString());
        logger.info("====================================================================>");
    }
}
